package com.cgly.medical.security;

import com.cgly.medical.entity.AccountModel;
//import com.cgly.medical.entity.AuthenticationBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import springfox.documentation.annotations.Cacheable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: CGLY
 * @description:
 * @author: chen di
 * @create: 2022-08-26 11:26
 */

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    SessionRegistry sessionRegistry;




    private static final Gson GSON = new Gson();

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        String verify_code = (String) request.getSession().getAttribute("verify_code");
        if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().contains(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            Map<String, String> loginData = new HashMap<>();
            try {
                loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (IOException e) {
            } finally {
                String code = loginData.get("code");
//                checkCode(response, code, verify_code);
            }
            String username = loginData.get(getUsernameParameter());
            String password = loginData.get(getPasswordParameter());
            if (username == null) {
                username = "";
            }
            if (password == null) {
                password = "";
            }
            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username, password);
            setDetails(request, authRequest);
            AccountModel principal = new AccountModel();
            principal.setUname(username);
            sessionRegistry.registerNewSession(request.getSession(true).getId(), principal);//存入session
            return this.getAuthenticationManager().authenticate(authRequest);
        } else {
            checkCode(response, request.getParameter("code"), verify_code);
            return super.attemptAuthentication(request, response);
        }
    }

    public void checkCode(HttpServletResponse resp, String code, String verify_code) {
        if (code == null || verify_code == null || "".equals(code) || !verify_code.toLowerCase().equals(code.toLowerCase())) {
            //验证码不正确
            throw new AuthenticationServiceException("验证码不正确");
        }
    }

//        if (!request.getMethod().equals("POST")) {
//            System.out.println("来源是: " + request.getMethod()+"请求，需要POST");
//            throw new AuthenticationServiceException(
//                    "来源是: " + request.getMethod()+"请求，需要POST");
//        }
//        String verify_code = (String) request.getSession().getAttribute("verify_code");//获取存在后台的code
//        // 解析前端传递的登录信息
//        LoginInfo loginInfo = null;
//        try {
//            loginInfo = translate(request);
//        } catch (IOException e) {
//            System.out.println("translate error："+e);
//            throw new AuthenticationServiceException("解析前端传递登录信息失败: " + e);
//        }
//        String username = loginInfo.getUsername();
//        String password = loginInfo.getPassword();
//
//        if (username == null) {
//            username = "";
//        }
//
//        if (password == null) {
//            password = "";
//        }
//
//        username = username.trim();
//
//        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
//                username, password);
//
//        // Allow subclasses to set the "details" property
//        setDetails(request, authRequest);
//
//        return this.getAuthenticationManager().authenticate(authRequest);
//}

    /**
     * 转换前端传递的 json
     *
     * @param request
     * @return LoginInfo
     */
    private LoginInfo translate(HttpServletRequest request) throws IOException {
        try(BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            String line = "";
            StringBuilder infoBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                infoBuilder.append(line);
            }

            return GSON.fromJson(infoBuilder.toString(), LoginInfo.class);
        }
    }

    @Data
    private static class LoginInfo {

        private String username;

        private String password;
    }
}